package com.nebula.controller;

import java.math.BigDecimal;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.demo.trade.config.Configs;
import com.google.common.collect.Maps;
import com.nebula.common.Const;
import com.nebula.common.ResponseCode;
import com.nebula.common.ServerResponse;
import com.nebula.pojo.User;
import com.nebula.service.IOrderService;

@Controller
@RequestMapping("/order")
public class OrderController {
	private static final Logger logger = LoggerFactory.getLogger(OrderController.class);
	
	@Autowired
	private IOrderService orderService;
	
	@RequestMapping("/create-order")
	@ResponseBody
	public ServerResponse createOrder(HttpSession session,@RequestParam("groupId")Integer groupId
			,@RequestParam("payment")BigDecimal payment,@RequestParam("paymentType")Integer paymentType){
		User user = (User) session.getAttribute(Const.USERINFO);
		if(user == null){
			return ServerResponse.createByErrorCodeMeaage(ResponseCode.NEED_LOGIN.getCode(), ResponseCode.NEED_LOGIN.getDesc());
		}
		return orderService.createOrder(user.getUsername(), groupId,payment,paymentType);
	}
	
	@RequestMapping(value = "/pay" , method = RequestMethod.POST)
	@ResponseBody
	public ServerResponse pay(HttpSession session,HttpServletRequest request
			,@RequestParam("orderNo")Long orderNo
			,@RequestParam("type") String type){
		User user = (User) session.getAttribute(Const.USERINFO);
		if(user == null){
			return ServerResponse.createByErrorCodeMeaage(ResponseCode.NEED_LOGIN.getCode(), ResponseCode.NEED_LOGIN.getDesc());
		}
		String path = request.getSession().getServletContext().getRealPath("qrCode");
		return orderService.pay(orderNo, user.getUsername(), path, type);
	}
	
	@RequestMapping("/alipay_callback")
	@ResponseBody
	public Object alipayCallback(HttpServletRequest request){
		
		Map<String, String> params = Maps.newHashMap();
		
		Map requestParams = request.getParameterMap();
		for(Iterator iter = requestParams.keySet().iterator();iter.hasNext();){
			String name = (String) iter.next();
			String []values = (String[]) requestParams.get(name);
			String valuesStr = "";
			for(int i = 0,len = values.length ; i < len ; i++){
				valuesStr = (i == values.length - 1) ? valuesStr + values[i] : valuesStr + values[i] + ",";
			}
			params.put(name, valuesStr);
		}
		
		logger.info("支付宝回调,sign:{},trade_status:{},参数:{}",params.get("sign"),params.get("trade_status"),params.toString());
		
		//验证回调是不是支付宝发的，并且避免重复通知
		params.remove("sign_type");
		try {
			boolean alipayRSACheckedV2 = AlipaySignature.rsaCheckV2(params, Configs.getAlipayPublicKey(), "utf-8", Configs.getSignType());
			if(!alipayRSACheckedV2){
				return ServerResponse.createByErrorMessage("非法请求，验证不通过，再恶意请求将找网警介入！");
			}
		} catch (AlipayApiException e) {
			logger.error("支付宝回调异常:",e);
		}
		
		ServerResponse serverResponse = orderService.aliCallback(params);
		if(serverResponse.isSuccess()){
			return Const.AlipayCallback.RESPONSE_SUCCESS;
		}
		return Const.AlipayCallback.RESPONSE_FAILED;
	}
	
	@RequestMapping(value = "/query_order_pay_status")
	@ResponseBody
	public ServerResponse<Boolean> queryOrderPayStatus(HttpSession session,@RequestParam("orderNo")Long orderNo){
		User user = (User) session.getAttribute(Const.USERINFO);
		if(user == null){
			return ServerResponse.createByErrorCodeMeaage(ResponseCode.NEED_LOGIN.getCode(), ResponseCode.NEED_LOGIN.getDesc());
		}
		
		ServerResponse serverResponse = orderService.queryOrderPayStatus(user.getUsername(), orderNo);
		if(serverResponse.isSuccess()){
			return ServerResponse.createBySuccess(true);
		}
		return ServerResponse.createBySuccess(false);
	}
	
	@RequestMapping("/order_detail")
	@ResponseBody
	public ServerResponse getOrderDetail(HttpSession session){
		User user = (User) session.getAttribute(Const.USERINFO);
		return orderService.queryOrderDetail(user.getUsername());
	}
}
